/**
 * 事件订阅，发布
 */
class Observer {
  public event = {};

  /**
   * 监听事件
   * @param {String} name 监听事件名称
   * @param {Function} fn 监听事件回调
   */
  on(name: string, fn: Function) {
    if (typeof fn !== 'function') {
      return new Error('Parameter error,The second argument must be a function');
    }
    if (!this.event[name]) {
      this.event[name] = [];
      this.event[name].push(fn);
    } else {
      this.event[name].push(fn);
    }

    return this;
  }

  /**
   * 删除监听事件
   * @param {String} name 关闭监听事件名称
   */
  off(name: string) {
    if (this.event[name]) {
      Object.keys(this.event).forEach(key => {
        if (name === key) {
          delete this.event[key];
        }
      });
    }
    return this;
  }

  /**
   * 触发事件
   * @param {String} name 触发事件名称
   * @param {[]} arg 参数
   */
  trigger(name: string, arg: any) {
    if (this.event[name] && Array.isArray(this.event[name])) {
      const event = this.event[name].slice();
      event.forEach((item: any, index: number) => {
        if (typeof item === 'function') {
          item.apply(null, [arg]);
        }
      });
    }
  }

  static instance: any;

  static getInstance() {
    if (!this.instance) {
      this.instance = new Observer();
    }
    return this.instance;
  }
}

export default Observer.getInstance();
